<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ include file="../common/header.jsp" %>
<div class="container-fluid p-t-15">
  <div class="row">
    <div class="col-lg-12">
      <div class="card">
        <!--  <div class="card-header">
          <h4>TreeGrid使用</h4>
        </div>-->
        <div class="card-body">
          
          <div id="toolbar2" class="toolbar-btn-action">
            <button type="button" class="btn btn-primary btn-sm m-r-5" onclick="toAddPage()"><i class="mdi mdi-plus"></i>添加</button>
          </div>
          
          <table class="tree-table"></table>
        </div>
      </div>
    </div>
    
  </div>
  
</div>
<%@ include file="../common/footer.jsp"%>
<script type="text/javascript">
// tree-grid使用
var data = JSON.parse('${requestScope.list}');

var $treeTable = $('.tree-table');
$treeTable.bootstrapTable({
    data: data,
    idField: 'id',
    uniqueId: 'id',
    dataType: 'jsonp',
    toolbar: '#toolbar2',
    columns: [
        {
            field: 'check',
            checkbox: true
        },
        {
            field: 'name',
            title: '名称'
        },
        {
            field: 'url',
            title: '地址'
        },
        {
            field: 'status',
            title: '状态',
            /*
             * 可以选择采用开关来处理状态显示
             * 或者采用上个示例的处理方式
             */
            formatter: function (value, row, index) {
                if (value == 0) {
                    is_checked = '';
                } else if (value == 1){
                    is_checked = 'checked="checked"';
                }
                result = '<label class="lyear-switch switch-primary lyear-status"><input type="checkbox" '+ is_checked +'><span  onClick="updateStatus('+ row.id +', '+ value +')"></span></label>';
                return result;
            },
        },
        {
            field: 'is_menu',
            title: '类型',
            formatter: function(value, row, index){
            	if(value == 1) {
            		return '<button onclick="updateMenu('+row.id+', '+value+')" class="btn btn-w-xs btn-round btn-success btn-xs">菜单</button>';
            	}
            	return '<button onclick="updateMenu('+row.id+', '+value+')" class="btn btn-w-xs btn-round btn-danger btn-xs">按钮</button>';
            }
        },
        {
            field: 'sort',
            title: '排序'
        },
        {
            field: 'date_entered',
            title: '创建时间'
        },
        {
            field: 'operate',
            title: '操作',
            align: 'center',
            events : {
                'click .role-add': function (e, value, row, index) {
                    add(row.id);
                },
                'click .role-delete': function (e, value, row, index) {
                    del(row.id);
                },
                'click .role-edit': function (e, value, row, index) {
                    update(row.id);
                }
            },
            formatter: operateFormatter
        }
    ],
    
    treeShowField: 'name',
    parentIdField: 'parent_id',
    
    onResetView: function(data) {
        $treeTable.treegrid({
            initialState: 'expanded', // 所有节点都折叠
            treeColumn: 1,
            //expanderExpandedClass: 'mdi mdi-folder-open',  // 可自定义图标样式
            //expanderCollapsedClass: 'mdi mdi-folder',
            onChange: function() {
                $treeTable.bootstrapTable('resetWidth');
            }
        });
        
        // 只展开树形的第一集节点
        //$treeTable.treegrid('getRootNodes').treegrid('expand');
    },
    onCheck: function(row) {
        var datas = $treeTable.bootstrapTable('getData');
        
        selectChilds(datas, row, 'id', 'pid', true); // 选择子类
        
        selectParentChecked(datas, row, 'id', 'parent_id'); // 选择父类
        
        $treeTable.bootstrapTable('load', datas);
    },
    
    onUncheck: function(row) {
        var datas = $treeTable.bootstrapTable('getData');
        selectChilds(datas, row, 'id', 'parent_id', false);
        $treeTable.bootstrapTable('load', datas);
    },
});
  
// 操作按钮
function operateFormatter(value, row, index) {
    return [
        '<a type="button" class="role-add btn btn-xs btn-default m-r-5" title="添加" data-toggle="tooltip"><i class="mdi mdi-plus"></i></a>',
        '<a type="button" class="role-edit btn btn-xs btn-default m-r-5" title="修改" data-toggle="tooltip"><i class="mdi mdi-pencil"></i></a>',
        '<a type="button" class="role-delete btn btn-xs btn-default" title="删除" data-toggle="tooltip"><i class="mdi mdi-delete"></i></a>'
    ].join('');
}

/**
 * 选中父项时，同时选中子项
 * @param datas 所有的数据
 * @param row 当前数据
 * @param id id 字段名
 * @param pid 父id字段名
 */
function selectChilds(datas,row,id,pid,checked) {
    for(var i in datas){
        if(datas[i][pid] == row[id]){
            datas[i].check=checked;
            selectChilds(datas,datas[i],id,pid,checked);
        };
    }
}

function selectParentChecked(datas,row,id,pid){
    for(var i in datas){
        if(datas[i][id] == row[pid]){
            datas[i].check=true;
            selectParentChecked(datas,datas[i],id,pid);
        };
    }
}

function add(id) {
	window.location.href = "${pageContext.request.contextPath}/admin/auth?method=Add&id="+id;
}
function del(id) {
    $.confirm({
        title: '警告',
        content: '您确定要删除吗？',
        type: 'orange',
        typeAnimated: false,
        buttons: {
            confirm: {
                text: '确定',
                btnClass: 'btn-orange',
                action: function(){
                	$.get("${pageContext.request.contextPath}/admin/auth?method=Delete&id="+id, function(res){
                		if(res.code == 200) {
                			lightyear.notify(res.message, 'success', 3000);
                			//$treeTable.bootstrapTable('refresh');
                			$treeTable.bootstrapTable('remove', {field: 'id',values: [id]});
                			//window.location.reload();
                		}else{
                			lightyear.notify(res.message, 'danger', 3000);
                		}
                	}, 'json');
                }
            },
            close: {
                text: '关闭',
            }
        }
    });
}
function update(id) {
    window.location.href = "${pageContext.request.contextPath}/admin/auth?method=Edit&id="+id;
}
function updateStatus(id, state) {
    var newstate = (state == 1) ? 0 : 1; // 发送参数值跟当前参数值相反
	lightyear.loading('show');
    $.ajax({
        type: "get",
        url: "${pageContext.request.contextPath}/admin/auth?method=updateStatus",
        data: {id: id, status: newstate},
        dataType: 'json',
        success: function (data) {
            if (data.code == '200') {
            	lightyear.notify(data.message, 'success', 3000);  
                $treeTable.bootstrapTable('updateCellById', {id: id, field: 'status', value: newstate});
            } else {
                lightyear.notify(data.message, 'danger', 3000);  
                $treeTable.bootstrapTable('updateCellById', {id: id, field: 'status', value: state}); // 因开关点击后样式是变的，失败也重置下
            }
        },
        error: function () {
            lightyear.notify('修改失败，请稍后再试', 'danger', 3000);  
        },
		complete: function(){
        	lightyear.loading('hide');
        }
    });
}

function updateMenu(id, is_menu){
	var newis_menu = (is_menu == 1) ? 0 : 1;
	lightyear.loading('show');
	$.ajax({
        type: "get",
        url: "${pageContext.request.contextPath}/admin/auth?method=updateMenu",
        data: {id: id, is_menu: newis_menu},
        dataType: 'json',
        success: function (data) {
            if (data.code == '200') {
            	lightyear.notify(data.message, 'success', 3000);  
                $treeTable.bootstrapTable('updateCellById', {id: id, field: 'is_menu', value: newis_menu});
            } else {
                lightyear.notify(data.message, 'danger', 3000);  
                $treeTable.bootstrapTable('updateCellById', {id: id, field: 'is_menu', value: is_menu}); // 因开关点击后样式是变的，失败也重置下
            }
        },
        error: function () {
            lightyear.notify('修改失败，请稍后再试', 'danger', 3000);  
        },
        complete: function(){
        	lightyear.loading('hide');
        }
    });
}

function toAddPage(){
	window.location.href="${pageContext.request.contextPath}/admin/auth?method=Add";
}

function test() {
    var selRows = $treeTable.bootstrapTable("getSelections");
    if(selRows.length == 0){
        alert("请至少选择一行");
        return;
    }
	console.log(selRows);

    var postData = "";
    $.each(selRows,function(i) {
        postData +=  this.id;
        if (i < selRows.length - 1) {
            postData += "， ";
        }
    });
    alert("你选中行的 id 为："+postData);
}
</script>